/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-09-29
 * Time: 8:39
 */
public class test_2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * 判断岛屿数量
     */
    static int num = 0;
    static int[] dx = {1, -1, 0, 0};
    static int[] dy = {0, 0, 1, -1};
    static int[][] vis;
    static int n;
    static int m;

    public static int solve(char[][] grid) {
        n = grid.length;
        m = grid[0].length;
        vis = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                boolean dfs = dfs(grid, i, j);
                if (dfs) {
                    num++;
                }
            }
        }
        return num;
    }

    private static boolean dfs(char[][] grid, int i, int j) {
        if (vis[i][j] == 1 || grid[i][j] == '0') {
            return false;
        }
        vis[i][j] = 1;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < n && y >= 0 && y < m &&
                    grid[x][y] == '1' && vis[x][y] == 0) {
                dfs(grid, x, y);
            }
        }
        return true;
    }

    public static void main(String[] args) {
        char[][] chars = {{'1', '1', '0', '0', '0'}, {'0', '1', '0', '1', '1'}, {'0', '0', '0', '1', '1'}, {'0', '0', '0', '0', '0'}, {'0', '0', '1', '1', '1'}};
        System.out.println(solve(chars));
    }
}
